from snack import snackclass,snack_actions
from apple import appleclass
# 定义游戏环境
'''
每吃一个苹果，蛇的长度和得分就会加一
撞墙或者吃到自己，得分减一
长时间不吃苹果，得分减一
'''
class environment(object):
    def __init__(self, map_size, nothing , dead, apple):
        self.map_size = map_size
        self.nothing = nothing
        self.dead = dead
        self.apple = appleclass(map_size)
        self.snack = snackclass(map_size)
        self.gameover = False
        self.applereward = apple
        self.time_after_last = 0
    # 重置游戏
    def reset(self):
        self.apple.position = np.random.randint(1, self.map_size ,2)
        self.apple.score = 0
        self.snack.position = np.random.randint(1, self.map_size ,2)
        self.snack.history_p = [self.apple.position.copy()]
        self.snack.snack_len = 4
        self.gameover = False
    # 获取当前游戏状态
    def getstate(self):
        return [self.snack.position ,self.snack.act ,self.snack.history_p,
                self.apple.position ,self.apple.score ,self.gameover]
    # 更新游戏状态
    def update(self ,act):
        reward = self.nothing
        Done = False
        if act ==0 :
            if not (self.snack.act == snack_actions['R']).all():
                self.snack.act = snack_actions['R']
        if act ==1 :
            if not (self.snack.act == snack_actions['L']).all():
                self.snack.act = snack_actions['L']
        if act ==2 :
            if not (self.snack.act == snack_actions['U']).all():
                self.snack.act = snack_actions['U']
        if act ==3 :
            if not (self.snack.act == snack_actions['D']).all():
                self.snack.act = snack_actions['D']
        # 移动
        self.snack.move()
        self.time_after_last += 1
        # 迭代一百次后停止
        if self.time_after_last == 100:
            self.gameover = True
            reward = self.dead
            self.time_after_last = 0
            Done = True
        # 吃到苹果
        if (self.snack.position == self.apple.position).all():
            self.apple.eaten()
            self.snack.snack_len += 1
            self.time_after_last = 0
            Done = True
        # 死亡
        elif self.snack.deadcheck(self.snack.position):
            self.gameover = True
            reward = self.dead
            self.time_after_last = 0
            Done = True

        return reward, Done, len(self.snack)